#!/usr/bin/env bash
source ./config/env.sh
clear

mkdir -p ${K8S_CA_DIR}/kubectl

cat > ${K8S_CA_DIR}/kubectl/admin-csr.json <<EOF
{
  "CN": "admin",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "system:masters",
      "OU": "4Paradigm"
    }
  ]
}
EOF

cd ${K8S_CA_DIR}/kubectl

cfssl gencert -ca=${K8S_CA_DIR}/admin/ca.pem \
  -ca-key=${K8S_CA_DIR}/admin/ca-key.pem \
  -config=${K8S_CA_DIR}/admin/ca-config.json \
  -profile=kubernetes admin-csr.json | cfssljson -bare admin


for master_ip in ${MASTER_IP}
do
    echo "=========================================== ${master_ip} ==========================================="
    ssh root@${master_ip} "test -e ${K8S_CA_DIR}/kubectl || mkdir -p ${K8S_CA_DIR}/kubectl"
    scp ${K8S_CA_DIR}/kubectl/admin* root@${master_ip}:${K8S_CA_DIR}/kubectl
done


${K8S_BIN_DIR}/kubectl config set-cluster kubernetes \
  --certificate-authority=${K8S_CA_DIR}/admin/ca.pem \
  --embed-certs=true \
  --server=${APISERVER} \
  --kubeconfig=kubectl.kubeconfig


${K8S_BIN_DIR}/kubectl config set-credentials admin \
  --client-certificate=${K8S_CA_DIR}/kubectl/admin.pem \
  --client-key=${K8S_CA_DIR}/kubectl/admin-key.pem \
  --embed-certs=true \
  --kubeconfig=kubectl.kubeconfig

${K8S_BIN_DIR}/kubectl config set-context kubernetes \
  --cluster=kubernetes \
  --user=admin \
  --kubeconfig=kubectl.kubeconfig
  

${K8S_BIN_DIR}/kubectl config use-context kubernetes --kubeconfig=kubectl.kubeconfig



for master_ip in ${MASTER_IP}
do
    echo "=========================================== ${master_ip} ==========================================="
    ssh root@${master_ip} "test -e ~/.kube/ || mkdir -p ~/.kube/"
    scp ${K8S_CA_DIR}/kubectl/kubectl.kubeconfig root@${master_ip}:~/.kube/config
done
